﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace BackLib.Networking
{
    public class Server : ITCPUser
    {
        private TcpListener tcpListener;
        private Thread listenThread;

        public Thread clientThread;

        public Server()
        {
            // Listen for Incoming Packets
            this.tcpListener = new TcpListener(IPAddress.Any, 3000);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }

        public void Dispose()
        {
            tcpListener.Stop();
            listenThread.Abort();
        }

        private void ListenForClients()
        {
            this.tcpListener.Start();

            while (true)
            {
                // Listen
                Handler.client = this.tcpListener.AcceptTcpClient();
                ConnectionChanged(true, true);
                clientThread = new Thread(ReceiveData);
                clientThread.Start();
            }
        }

        #region ITCPUser Members

        public void SendData(byte[] Buffer)
        {
            Handler.SendData(Buffer);
        }

        public void ReceiveData()
        {
            Handler.ReadBytes();
        }

        #endregion
    }
}
